package com.example.myapplication.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.DriveFileMove
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.example.myapplication.ui.components.BreadcrumbNavigation
import com.example.myapplication.ui.components.ErrorState
import com.example.myapplication.ui.components.LoadingState
import com.example.myapplication.ui.components.MoveItemDialog
import com.example.myapplication.viewmodel.ItemDetailViewModel
import com.example.myapplication.viewmodel.NavigationEvent
import java.text.SimpleDateFormat
import java.util.*

/**
 * 物品详情界面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemDetailScreen(
    itemId: String,
    onNavigateBack: () -> Unit,
    onNavigateToStorageDetail: (String) -> Unit,
    viewModel: ItemDetailViewModel = hiltViewModel()
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()

    LaunchedEffect(Unit) {
        viewModel.navigationEvent.collect { event ->
            when (event) {
                is NavigationEvent.NavigateToSpace -> onNavigateToStorageDetail(event.spaceId)
                is NavigationEvent.NavigateBack -> onNavigateBack()
            }
        }
    }

    LaunchedEffect(itemId) {
        viewModel.loadItemDetails(itemId)
    }

    if (uiState.isMoveDialogVisible) {
        uiState.item?.let {
            MoveItemDialog(
                itemToMove = it,
                allSpaces = uiState.allSpaces,
                onDismiss = { viewModel.onMoveDialogDismiss() },
                onConfirm = { destinationSpaceId ->
                    viewModel.migrateItem(destinationSpaceId)
                }
            )
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { 
                    if (uiState.breadcrumbs.isNotEmpty()) {
                        BreadcrumbNavigation(
                            breadcrumbs = uiState.breadcrumbs,
                            onBreadcrumbClick = { breadcrumbId ->
                                // 如果是主页，则导航回主页
                                if (breadcrumbId == "root") {
                                    onNavigateBack()
                                } else {
                                    onNavigateToStorageDetail(breadcrumbId)
                                }
                            }
                        )
                    } else {
                        Text(uiState.item?.name ?: "物品详情")
                    }
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = { 
                        // TODO: 实现编辑物品功能
                        // 可以触发编辑对话框或导航到编辑页面
                    }) {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "编辑物品"
                        )
                    }
                    IconButton(onClick = { viewModel.onMoveClicked() }) {
                        Icon(
                            imageVector = Icons.Default.DriveFileMove,
                            contentDescription = "移动物品"
                        )
                    }
                }
            )
        }
    ) { paddingValues ->
        when {
            uiState.isLoading -> {
                LoadingState(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    message = "加载物品详情..."
                )
            }
            uiState.errorMessage != null -> {
                ErrorState(
                    message = uiState.errorMessage ?: "未知错误",
                    onRetry = { viewModel.loadItemDetails(itemId) },
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                )
            }
            uiState.item != null -> {
                val item = uiState.item!!
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues)
                ) {
                                        AsyncImage(
                        model = item.imagePath,
                        contentDescription = item.name,
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(250.dp),
                        contentScale = ContentScale.Crop
                    )

                    Column(modifier = Modifier.padding(16.dp)) {
                        Text(
                            text = item.name,
                            style = MaterialTheme.typography.headlineMedium
                        )

                        Spacer(modifier = Modifier.height(8.dp))

                        Text(
                            text = "数量: ${item.quantity}",
                            style = MaterialTheme.typography.bodyLarge
                        )

                        Spacer(modifier = Modifier.height(8.dp))

                        item.description?.let {
                            Text(
                                text = it,
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }

                        Spacer(modifier = Modifier.height(16.dp))
                        Divider()
                        Spacer(modifier = Modifier.height(16.dp))

                        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
                        Text(
                            text = "创建于: ${dateFormat.format(Date(item.createdAt))}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "更新于: ${dateFormat.format(Date(item.updatedAt))}",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }
        }
    }
}